"use client";

import { FileItem, useFiles } from "@/hooks/useFiles";
import { Check, ChevronDown, ChevronRight, Folder } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "./button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./dialog";
import { Input } from "./input";

interface MoveDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    sourceItem: FileItem | null;
    onMove: (sourcePath: string, targetPath: string, type: "file" | "directory") => void;
}

interface TreeNode {
    path: string;
    name: string;
    type: "directory";
    children?: TreeNode[];
    expanded?: boolean;
}

export function MoveDialog({ open, onOpenChange, sourceItem, onMove }: MoveDialogProps) {
    const [selectedPath, setSelectedPath] = useState<string | undefined>(undefined);
    const [searchTerm, setSearchTerm] = useState("");
    const [treeData, setTreeData] = useState<TreeNode[]>([]);
    const [loading, setLoading] = useState(false);

    const { data: filesData, isLoading } = useFiles({
        path: "",
        search: "",
        sortBy: "name",
        sortOrder: "asc",
    });

    useEffect(() => {
        if (open) {
            setSelectedPath(undefined);
            setSearchTerm("");
            loadTreeData();
        }
    }, [open]);

    const loadTreeData = async () => {
        setLoading(true);
        try {
            // 获取根目录的所有文件夹
            const response = await fetch("/api/files/list?path=&sortBy=name&sortOrder=asc");
            if (response.ok) {
                const data = await response.json();
                const directories = data.data?.filter((item: FileItem) => item.type === "directory") || [];

                // 构建树形结构
                const tree = await buildTreeStructure(directories);
                setTreeData(tree);
            }
        } catch (error) {
            console.error("Failed to load tree data:", error);
        } finally {
            setLoading(false);
        }
    };

    const buildTreeStructure = async (directories: FileItem[]): Promise<TreeNode[]> => {
        const tree: TreeNode[] = [];

        for (const dir of directories) {
            const node: TreeNode = {
                path: dir.path,
                name: dir.name,
                type: "directory",
                expanded: false,
                children: [],
            };

            // 递归获取子目录
            try {
                const response = await fetch(`/api/files/list?path=${encodeURIComponent(dir.path)}&sortBy=name&sortOrder=asc`);
                if (response.ok) {
                    const data = await response.json();
                    const subDirectories = data.data?.filter((item: FileItem) => item.type === "directory") || [];
                    if (subDirectories.length > 0) {
                        node.children = await buildTreeStructure(subDirectories);
                    }
                }
            } catch (error) {
                console.error(`Failed to load children for ${dir.path}:`, error);
            }

            tree.push(node);
        }

        return tree;
    };

    const toggleNode = (nodePath: string) => {
        const updateNode = (nodes: TreeNode[]): TreeNode[] => {
            return nodes.map((node) => {
                if (node.path === nodePath) {
                    return { ...node, expanded: !node.expanded };
                }
                if (node.children) {
                    return { ...node, children: updateNode(node.children) };
                }
                return node;
            });
        };
        setTreeData(updateNode(treeData));
    };

    const handleSelectPath = (path: string) => {
        setSelectedPath(path);
    };

    const handleConfirmMove = () => {
        if (!sourceItem) return;

        if (selectedPath === sourceItem.path) {
            toast.error("不能移动到原位置");
            return;
        }

        // 如果是文件夹，检查是否试图移动到自己的子文件夹
        if (sourceItem.type === "directory" && selectedPath && selectedPath.startsWith(sourceItem.path + "/")) {
            toast.error("不能将文件夹移动到自己的子文件夹中");
            return;
        }

        // 构建目标路径
        const targetPath = selectedPath !== undefined ? (selectedPath ? `${selectedPath}/${sourceItem.name}` : sourceItem.name) : sourceItem.name;

        onMove(sourceItem.path, targetPath, sourceItem.type);
        onOpenChange(false);
    };

    const isNodeDisabled = (nodePath: string): boolean => {
        if (!sourceItem || sourceItem.type !== "directory") return false;

        // 如果是文件夹，检查是否是当前文件夹或其子文件夹
        return nodePath === sourceItem.path || nodePath.startsWith(sourceItem.path + "/");
    };

    const renderTreeNode = (node: TreeNode, level: number = 0) => {
        const hasChildren = node.children && node.children.length > 0;
        const isSelected = selectedPath === node.path;
        const isDisabled = isNodeDisabled(node.path);

        return (
            <div key={node.path}>
                <div
                    className={`flex items-center space-x-2 p-2 rounded-md transition-colors ${isDisabled ? "opacity-50 cursor-not-allowed bg-muted/50" : "cursor-pointer hover:bg-accent"} ${
                        isSelected ? "bg-accent" : ""
                    }`}
                    style={{ paddingLeft: `${level * 20 + 8}px` }}
                    onClick={() => !isDisabled && handleSelectPath(node.path)}
                >
                    <div className="flex items-center space-x-1">
                        {hasChildren && (
                            <button
                                onClick={(e) => {
                                    e.stopPropagation();
                                    if (!isDisabled) {
                                        toggleNode(node.path);
                                    }
                                }}
                                className={`p-1 rounded ${isDisabled ? "opacity-50 cursor-not-allowed" : "hover:bg-muted"}`}
                                disabled={isDisabled}
                            >
                                {node.expanded ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
                            </button>
                        )}
                        {!hasChildren && <div className="w-5" />}
                    </div>

                    <div className="flex-shrink-0">{isSelected ? <Check className="h-4 w-4 text-primary" /> : <Folder className={`h-4 w-4 ${isDisabled ? "text-muted-foreground" : "text-blue-500"}`} />}</div>

                    <div className="flex-1 min-w-0">
                        <p className={`text-sm font-medium truncate ${isDisabled ? "text-muted-foreground" : ""}`}>
                            {node.name}
                            {isDisabled && sourceItem?.type === "directory" && <span className="text-xs text-muted-foreground ml-2">(当前文件夹)</span>}
                        </p>
                    </div>
                </div>

                {node.expanded && node.children && <div>{node.children.map((child) => renderTreeNode(child, level + 1))}</div>}
            </div>
        );
    };

    const filterTree = (nodes: TreeNode[], searchTerm: string): TreeNode[] => {
        if (!searchTerm) return nodes;

        return nodes
            .filter((node) => {
                const matchesSearch = node.name.toLowerCase().includes(searchTerm.toLowerCase());
                const hasMatchingChildren = node.children && filterTree(node.children, searchTerm).length > 0;
                return matchesSearch || hasMatchingChildren;
            })
            .map((node) => ({
                ...node,
                children: node.children ? filterTree(node.children, searchTerm) : undefined,
            }));
    };

    const filteredTree = filterTree(treeData, searchTerm);

    if (!sourceItem) return null;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle>
                        移动 {sourceItem.type === "directory" ? "文件夹" : "文件"}: {sourceItem.name}
                    </DialogTitle>
                </DialogHeader>

                <div className="space-y-4">
                    {/* 当前选择的目标路径 */}
                    <div className="p-3 bg-muted rounded-lg">
                        <p className="text-sm text-muted-foreground mb-1">目标位置:</p>
                        <p className="text-sm font-medium">{selectedPath !== undefined ? (selectedPath ? `/${selectedPath}/${sourceItem.name}` : `/${sourceItem.name}`) : "请选择目标位置"}</p>
                    </div>

                    {/* 搜索框 */}
                    <div className="relative">
                        <Input placeholder="搜索文件夹..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                    </div>

                    {/* 根目录选项 */}
                    <div className="border rounded-lg">
                        {(() => {
                            const isRootDisabled = sourceItem?.type === "directory" && sourceItem.path === "";
                            return (
                                <div
                                    className={`flex items-center space-x-3 p-2 rounded-md transition-colors ${isRootDisabled ? "opacity-50 cursor-not-allowed bg-muted/50" : "cursor-pointer hover:bg-accent"} ${
                                        selectedPath === "" ? "bg-accent" : ""
                                    }`}
                                    onClick={() => !isRootDisabled && handleSelectPath("")}
                                >
                                    <div className="flex-shrink-0">
                                        {selectedPath === "" ? <Check className="h-4 w-4 text-primary" /> : <Folder className={`h-4 w-4 ${isRootDisabled ? "text-muted-foreground" : "text-blue-500"}`} />}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className={`text-sm font-medium truncate ${isRootDisabled ? "text-muted-foreground" : ""}`}>
                                            根目录
                                            {isRootDisabled && <span className="text-xs text-muted-foreground ml-2">(当前文件夹)</span>}
                                        </p>
                                    </div>
                                </div>
                            );
                        })()}
                    </div>

                    {/* 文件夹树形结构 */}
                    <div className="border rounded-lg max-h-64 overflow-y-auto">
                        {loading ? (
                            <div className="flex items-center justify-center p-8">
                                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                            </div>
                        ) : filteredTree.length === 0 ? (
                            <div className="flex flex-col items-center justify-center p-8 text-muted-foreground">
                                <Folder className="h-8 w-8 mb-2" />
                                <p className="text-sm">{searchTerm ? "没有找到匹配的文件夹" : "没有文件夹"}</p>
                            </div>
                        ) : (
                            <div className="space-y-1">{filteredTree.map((node) => renderTreeNode(node))}</div>
                        )}
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex justify-end space-x-2 pt-4">
                        <Button variant="outline" onClick={() => onOpenChange(false)}>
                            取消
                        </Button>
                        <Button onClick={handleConfirmMove} disabled={selectedPath === undefined}>
                            确认移动
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}
